<template>

  <div class="divBox relative">
    <el-card class="box-card" style="min-height: 85vh">

      <el-collapse v-model="activeNames">
          <el-collapse-item name="1">

            <template slot="title">
<!--              <el-badge value="new" class="item">-->
              <el-badge value="" class="item">
                我的账号
                <i class="el-icon-connection" style="color:blue" v-if="im.isconnection"></i>
                <i class="el-icon-loading" style="color:red" v-if="im.isconnection==false"></i>
              </el-badge>
            </template>
            <div style="margin-top: 10px">
              <a-badge :count="item.unread" v-for="item in dataList" >
                <el-tag :type="im.selectedUserId==item.userid?'success':'info'"
                        style="border-radius: 0px !important;margin-left: 5px;margin-top: 5px" @click="getFriendsList(item)">
                  {{item.userniname}}
                  <a-icon v-if="item.gender==1" type="man" style="color: blue"/>
                  <a-icon v-if="item.gender==2" type="woman" style="color: deeppink"/>
                </el-tag>
              </a-badge>
            </div>
          </el-collapse-item>

      </el-collapse>










          <el-card v-for="item in dataList" :hidden="im.selectedUserId===item.userid?false:true">
            <el-tabs tab-position="left" type="border-card" style="height: 90vh;overflow-y:auto">
              <el-tab-pane v-for="item1 in item.datalist" stretch="true">
                <span slot="label"  @click="getMsg(item1)">{{item1.userniname}}
                        <a-badge :count="item1.unread">
                          <a-avatar :src="item1.userimg"/>
                        </a-badge>
                  <a-icon v-if="item1.gender==1" type="man" style="color: blue"/>
                  <a-icon v-if="item1.gender==2" type="woman" style="color: deeppink"/>

                </span>
                  <el-card style="height: 55vh;overflow-y:auto">

                    <a-list
                      class="demo-loadmore-list"
                      item-layout="horizontal"
                      :data-source="item1.datalist"
                    >
                      <!--

                        <div
                        v-if="showLoadingMore"
                        slot="loadMore"
                        :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }"
                      >
                        <a-spin v-if="loadingMore" />
                        <a-button v-else @click="onLoadMore">
                          loading more
                        </a-button>
                      </div>

                      -->



                      <a-list-item slot="renderItem" slot-scope="item2, index">
                        <a-list-item-meta
                          :description="item2.payload.searchableContent"
                        >
                          <a slot="title" >{{item2.sender==im.selectedUser.userid?im.selectedUser.userniname:item1.userniname}}</a>
                          <a-avatar slot="avatar" :src="item2.sender==im.selectedUser.userid?im.selectedUser.userimg:item1.userimg"/>
                        </a-list-item-meta>
                        <div>{{item2.creatTime}}</div>
                      </a-list-item>
                    </a-list>


<!--                    <template>-->
<!--                      <ul style="height: 800px;overflow-y:auto" >-->
<!--                        <li v-for="item in dataList" class="infinite-list-item">{{item1.userniname}}</li>-->
<!--                        <li v-for="item in dataList" class="infinite-list-item">{{item1.userniname}}</li>-->
<!--                        <li v-for="item in dataList" class="infinite-list-item">{{item1.userniname}}</li>-->
<!--                        <li v-for="item in dataList" class="infinite-list-item">{{item1.userniname}}</li>-->
<!--                      </ul>-->
<!--                    </template>-->
                  </el-card>
                <a-comment>
                  <a slot="author">{{im.selectedUser.userniname}}
                    <a-icon v-if="im.selectedUser.gender==1" type="man" style="color: blue"/>
                    <a-icon v-if="im.selectedUser.gender==2" type="woman" style="color: deeppink"/>
                  </a>
                  <a-avatar
                    slot="avatar"
                    :src="im.selectedUser.userimg"
                  />

                  <div slot="content">
                    <a-form-item>
                      <a-textarea :rows="4"  v-model="msg.content" @keyup.enter.native="sendMsg(item1.userid)"/>
                    </a-form-item>
                    <a-form-item>
                      <a-button html-type="submit" type="primary" :disabled="msg.content.length==0?true:False" :loading="submitting" @click="sendMsg(item1.userid)">
                        Add Comment
                      </a-button>
                    </a-form-item>
                  </div>
                </a-comment>


              </el-tab-pane>
            </el-tabs>

          </el-card>



    </el-card>
    <!-- 表单弹窗, 新增数据和修改数据 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <update  v-if="addOrUpdateVisible" ref="update" @refreshDataList="getDataList"></update>
  </div>
</template>
<style>
  /*.el-tabs--card {*/
  /*  height: calc(100vh - 110px);*/
  /*  !* overflow-y: auto; *!*/
  /*}*/
  /*.el-tab-pane {*/
  /*  height: calc(100vh - 110px);*/
  /*  overflow-y: auto;*/
  /*}*/
  .el-tabs__item {
    height: 60px !important;
    padding-top: 10px !important;
  }
</style>
<script>
  import api from '@/api/api'
  import {checkPermi} from "@/utils/permission";
  import * as systemAdminApi from '@/api/systemadmin'
  import Cookies from 'js-cookie'
  let socket;
  export default {
    components: {
    },
    data () {
      return {
        listData:[],
        dataList: [],
        adminid:'',
        submitting:false,
        activeNames:['1'],
        im:{
          selectedUserId:'',
          selectedUser:{},
          isconnection:false
        },
        msg:{
          content:''
        },
        queryForm: {
          adminid:'',
          userexist:1
        },
        tableForm:{
          pageIndex: 1,
          pageSize: 200,
          total: 0,
        },
        sort:{
          order:'desc',
          column:'createtime'
        },
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        dataRule: {
          adminid: [
            { required: true, message: '请选择运营', trigger: 'blur' }
          ]
        },
      }
    },

    mounted () {
      //this.getDataList()
      this.openSocket()
    //  this.handleGetAdminList()
    },
    methods: {
      checkPermi,
      // 每页数
      sizeChangeHandle (val) {
        this.tableForm.pageSize = val
        this.tableForm.pageIndex = 1
        //this.getDataList()
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.dataListLoading = true
        let postData={
          'order':'asc',
          'column':'createtime'
        }



        Object.assign(postData,this.queryForm, this.tableForm)
        let JavaInfo = JSON.parse(Cookies.get('JavaInfo'))
        postData.adminid=JavaInfo.id;
        api.post('rest/vabc/userEntity/getUserList',postData).then(res => {
          let datalist=res.datalist;
          // for (let index in datalist){
          //   datalist[index].datalist=[]
          // }
          this.dataList=datalist
          this.tableForm.total=res.total
        }).finally(() => {
          this.dataListLoading = false
        });
      },
      getFriendsList (item) {
        let userid=item.userid;
        this.im.selectedUser=item
        this.im.selectedUserId=userid
        this.activeNames=['0']
        this.dataListLoading = true
        this.dataListLoading = true
        let postData={
          'userid':userid,
          'order':'desc',
          'column':'createtime'
        }
        api.post('rest/vabc/friends/list',postData).then(res => {
          let datalist=res.datalist;
          for (let index in this.dataList){
            if(this.dataList[index].userid==userid)
            {
              this.dataList[index].datalist=datalist
            }
          }
        }).finally(() => {
          this.dataListLoading = false
        });
      },
      getMsg(user){
        let postData={
          fUserId:user.userid,
          mkUserId:this.im.selectedUser.userid,
        }
        api.post('rest/vabc/friends/getFriendsMsglist',postData).then(res => {
         // console.error(user)
         // console.error(res.datalist)
          user.datalist=res.datalist
          // this.$message.success("分配成功")
          // this.getDataList()
        })
      },
      sendMsg(toid){
        let postData={
          toid:toid,
          fid:this.im.selectedUser.userid,
          content:this.msg.content.replaceAll("\n",""),
          type:''
        }
        api.post('rest/vabc/im/sendMsg',postData).then(res => {
          this.msg.content=''
          // this.$message.success("分配成功")
          // this.getDataList()
        })
      }
      ,
    openSocket() {
        let that=this;
    if(typeof(WebSocket) == "undefined") {
      that.$message.error("您的浏览器不支持WebSocket,请更换为Chorm浏览器");
    }else{
      let JavaInfo = JSON.parse(Cookies.get('JavaInfo'))
      //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
      //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
      //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
     // var socketUrl="http://localhost:8080/api/imserver/{userId}/"+$("#userId").val();
      var socketUrl="http://182.92.162.207:8080/api/imserver/"+JavaInfo.id;
     // var socketUrl="http://localhost:8080/api/imserver/"+JavaInfo.id;
      socketUrl=socketUrl.replace("https","ws").replace("http","ws");
      //console.log(socketUrl);
      if(socket!=null){
        socket.close();
        socket=null;
      }
      socket = new WebSocket(socketUrl);
      //打开事件
      socket.onopen = function() {
        that.$message.success("服务器已连接")
        that.im.isconnection=true

        //socket.send("这是来自客户端的消息" + location.href + new Date());
      };
      //获得消息事件
      socket.onmessage = function(msg) {
        let data=JSON.parse(msg.data);
        if (that.im.selectedUser.userid!=data.mkUserId){

          for (let index in that.dataList){
            if (that.dataList[index].userid==data.mkUserId){
              //获取所有未读消息
                that.dataList[index].unread=data.unreadAll;
              that.$message.success("其他账号有新消息")
              return
            }
        }
        }

        for (let index in that.dataList){
         // console.error("this.dataList[index].userid",that.dataList[index].userid);

          if (that.dataList[index].userid==data.mkUserId){
            //获取所有未读消息
            that.dataList[index].unread=data.unreadAll;

            let f_itemList=that.dataList[index].datalist;

//            console.error("that.dataList[index]",that.dataList[index])
  //          console.error("f_itemList",f_itemList)
          //  console.error("f_itemList.datalist",f_itemList.datalist)

            //f_itemList.datalist.push(data)

            for (let index1 in f_itemList){
           //  console.error("f_itemList[index1].userid", f_itemList[index1].userid,data.fUserId);
              if(f_itemList[index1].userid==data.fUserId)
              {
              //  console.error("f_itemList[index1]",f_itemList[index1].datalist)
                //获取朋友所有未读消息
                f_itemList[index1].unread=data.unreadF
                f_itemList[index1].datalist.unshift(data)
                return;
              }
            }


          }
        }

        //发现消息进入    开始处理前端触发逻辑
      };
      //关闭事件
      socket.onclose = function() {
        //that.$message.error("服务器已断开")
        that.im.isconnection=false

      };
      //发生了错误事件
      socket.onerror = function() {
        //that.$message.error("服务器已断开")
        that.im.isconnection=false
      }
    }
  }
    }
  }
</script>
